package com.jzy.message.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jzy.message.R;
import com.jzy.message.activities.adapter.ChatAdapter;
import com.jzy.message.activities.adapter.FaceVPAdapter;
import com.jzy.message.activities.base.BaseApplication;
import com.jzy.message.control.view.DropdownListView;
import com.jzy.message.db.ChatMsgDao;
import com.jzy.message.db.SessionDao;
import com.jzy.message.entity.xmpp.Msg;
import com.jzy.message.entity.xmpp.Session;
import com.jzy.message.listener.MsgListener;
import com.jzy.message.util.SoundManager;
import com.jzy.message.util.common.CommUtility;
import com.jzy.message.util.file.FileUtils;
import com.jzy.message.util.photo.Constants;
import com.jzy.message.util.xmpp.Const;
import com.jzy.message.util.xmpp.ExpressionUtil;
import com.jzy.message.util.xmpp.PreferencesUtils;
import com.jzy.message.util.xmpp.XmppUtil;

import org.jivesoftware.smack.XMPPException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 聊天界面
 * @author 白玉梁
 * @blog http://blog.csdn.net/baiyuliang2013
 * @weibo http://weibo.com/274433520
 * 
 * */
@SuppressLint("SimpleDateFormat")
/*public class ChatActivity extends Activity implements OnClickListener,DropdownListView.OnRefreshListenerHeader {*/
	public class ChatActivity extends Activity implements OnClickListener{
	private ChatActivity thisChatActivity;
	private ViewPager mViewPager;
	private LinearLayout mDotsLayout;
	private EditText input;
	private TextView send;
	private DropdownListView mListView;
	private ChatAdapter mLvAdapter;
	private ChatMsgDao msgDao;//读取数据库操作
	private SessionDao sessionDao;
	
	private LinearLayout chat_face_container,chat_add_container;
	private ImageView image_face;//表情图标
	private ImageView image_add;//更多图标

	private ImageView iv_common_back;//返回图标
	
	private TextView tv_title;//图片

	private TextView tv_pic,
			tv_video,
			tv_camera,
			tv_calling,
			tv_loc;//位置
	
	//表情图标每页6列4行
	private int columns = 6;
	private int rows = 4;
	//每页显示的表情view
	private List<View> views = new ArrayList<View>();
	//表情列表
	private List<String> staticFacesList;
	//消息
	private List<Msg> listMsg;
	private SimpleDateFormat sd;
	private NewMsgReciver newMsgReciver;
	private MsgOperReciver msgOperReciver;
	private LayoutInflater inflater;
	private int offset;
	private String I,YOU;//为了好区分，I就是自己，YOU就是对方
	SoundManager snd;
	private Button btn_chat_voice,btn_chat_keyboard,btn_speak;
	RelativeLayout layout_record;
	TextView tv_voice_tips;
	ImageView iv_record;
	/** 语音文件保存路径 */
	private String mFileName = null;
	/** 按住说话按钮 */
	private Button mBtnVoice;
	/** 用于语音播放 */
	private MediaPlayer mPlayer = null;
	/** 用于完成录音 */
	private MediaRecorder mRecorder = null;
	private String avatar;//对方头像
	private String avatarmy;
	private String nicheng;//对方的昵称
	//视频通话
	public static LocalBroadcastManager localBroadcastManager;//注册广播
	int qq;
	private static final String LOG_TAG = "AudioRecordTest";
	private static final String PATH = "/sdcard/MyVoiceForder/Record/";
	private static final int POLL_INTERVAL = 300;
	private Handler mHandler1 = new Handler();
	
	private Runnable mPollTask = new Runnable() {
		public void run() {
			double amp = mRecorder.getMaxAmplitude() / 2700.0;
			updateDisplay(amp);
			mHandler1.postDelayed(mPollTask, POLL_INTERVAL);

		}
	};

	private Runnable mSleepTask = new Runnable() {
		public void run() {
		}
	};
	private void updateDisplay(double signalEMA) {

		switch ((int) signalEMA) {
		case 0:
		case 1:
		case 2:
			iv_record.setImageResource(R.drawable.chat_icon_voice1);
			break;
		case 3:
		case 4:
		case 5:
			iv_record.setImageResource(R.drawable.chat_icon_voice2);
			break;
		case 6:
		case 7:
		case 8:
			iv_record.setImageResource(R.drawable.chat_icon_voice3);
			break;
		case 9:
		case 10:
		case 11:
			iv_record.setImageResource(R.drawable.chat_icon_voice4);
			break;
		case 12:
		case 13:
		case 14:
			iv_record.setImageResource(R.drawable.chat_icon_voice5);
			break;
		default:
			iv_record.setImageResource(R.drawable.chat_icon_voice6);
			break;
		}
	}
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				mLvAdapter.notifyDataSetChanged();
				break;
			}
		}
	};
	
	@SuppressLint("ShowToast")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_main_chat);
		//添加语音提示
		snd = new SoundManager(getApplicationContext());
		qq = snd.load(R.raw.qq);
		/*try {
			Thread.sleep(1000);
			snd.play(qq);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/

		thisChatActivity=this;
		localBroadcastManager=LocalBroadcastManager.getInstance(this);//注册广播
		I= PreferencesUtils.getSharePreStr(this, "username");
		YOU=getIntent().getStringExtra("from");
		avatar=getIntent().getStringExtra("avatar");
		avatarmy=getIntent().getStringExtra("avatarmy");
		nicheng=getIntent().getStringExtra("nicheng");
		inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		tv_title=(TextView) findViewById(R.id.tv_common_title);
		tv_title.setText(nicheng);
		iv_common_back=(ImageView)findViewById(R.id.iv_common_back);
		iv_common_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				thisChatActivity.finish();
			}
		});
		sd=new SimpleDateFormat("MM-dd HH:mm");
		msgDao=new ChatMsgDao(this);
		sessionDao=new SessionDao(this);//当前会话
		msgOperReciver=new MsgOperReciver(); //广播接收器
		newMsgReciver=new NewMsgReciver();//新消息
		IntentFilter intentFilter=new IntentFilter(Const.ACTION_MSG_OPER);
		registerReceiver(msgOperReciver, intentFilter);
		intentFilter=new IntentFilter(Const.ACTION_NEW_MSG);
		registerReceiver(newMsgReciver, intentFilter);
		staticFacesList= ExpressionUtil.initStaticFaces(this);
		//初始化控件
		initViews();
		//初始化表情
		//initViewPager();
		//初始化更多选项（即表情图标右侧"+"号内容）
		initAdd();
		//初始化数据
		initData();
		//更新与该用户的聊天记录全部为已读
		//updateMsgToReaded();
	}
	
	
	private void updateMsgToReaded() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				msgDao.updateAllMsgToRead(YOU,I);
			}
		}).start();
	}


	/**
	 * 初始化控件
	 */
	private void initViews() {
		mListView = (DropdownListView) findViewById(R.id.message_chat_listview);
		//表情图标
		image_face=(ImageView) findViewById(R.id.image_face);
		//更多图标
		image_add=(ImageView) findViewById(R.id.image_add);
		//表情布局
		chat_face_container=(LinearLayout) findViewById(R.id.chat_face_container);
		//更多
		chat_add_container=(LinearLayout) findViewById(R.id.chat_add_container);
		
		mViewPager = (ViewPager) findViewById(R.id.face_viewpager);
		mViewPager.setOnPageChangeListener(new PageChange());
		//表情下小圆点
		mDotsLayout = (LinearLayout) findViewById(R.id.face_dots_container);
		input = (EditText) findViewById(R.id.input_sms);
		send = (TextView) findViewById(R.id.send_sms);
		input.setOnClickListener(this);
		input.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				Log.i("a",String.valueOf(start)+"-"+String.valueOf(before)+"-"+String.valueOf(count));
				if(count>0)//添加文字
				{
					if(send.getVisibility()==View.GONE)
						setaddsendrelation(R.id.send_sms);
				}
				/*if(start==0&&count==0)//文字删空了
				{
					if(image_add.getVisibility()==View.GONE)
						setaddsendrelation(R.id.image_add);
				}*/
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		
		//表情按钮
		image_face.setOnClickListener(this);
		//更多按钮
		//image_add.setOnClickListener(this);
		// 发送
		send.setOnClickListener(this);
		
	//	mListView.setOnRefreshListenerHead(this);
		mListView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				if(arg1.getAction()==MotionEvent.ACTION_DOWN){
					if(chat_face_container.getVisibility()==View.VISIBLE){
						chat_face_container.setVisibility(View.GONE);
					}
					if(chat_add_container.getVisibility()==View.VISIBLE){
						chat_add_container.setVisibility(View.GONE);
					}
					hideSoftInputView();
				}
				return false;
			}
		});
		btn_speak=(Button)findViewById(R.id.btn_speak);
		btn_speak.setOnTouchListener(new OnTouchListener() {
			long beforeTime;
			long afterTime;
			int timeDistance;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				String dir = null;
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					beforeTime = System.currentTimeMillis();
					try {
						v.setPressed(true);
						layout_record.setVisibility(View.VISIBLE);
						tv_voice_tips
								.setText(getString(R.string.voice_cancel_tips));
						mHandler1.postDelayed(new Runnable() {
							public void run() {
								layout_record.setVisibility(View.VISIBLE);
							}
						}, 300);
					} catch (Exception e) {
					}
					dir = startVoice();
					mHandler1.postDelayed(mPollTask, POLL_INTERVAL);
					break;
				case MotionEvent.ACTION_UP:
					afterTime = System.currentTimeMillis();
					System.out.println(timeDistance + "声音录制时间");
					v.setPressed(false);
					layout_record.setVisibility(View.INVISIBLE);
					mHandler1.removeCallbacks(mSleepTask);
					mHandler1.removeCallbacks(mPollTask);
					
					stopVoice();
					
					String voiceFile = XmppUtil.GetImageStr(mFileName);
					
					if ("".equals(mFileName)) {
						Toast.makeText(ChatActivity.this, "不能为空",
								Toast.LENGTH_SHORT).show();
					} else {
						// (afterTime-beforeTime)/1000
						try {
							if ((afterTime - beforeTime) < 500) {
								Toast.makeText(getApplicationContext(),
										"录音时间太短！", Toast.LENGTH_SHORT).show();
								File file = new File(mFileName);
								file.delete();
							} else {
								/*sendMessage(voiceFile + "&"
										+ (afterTime - beforeTime) / 1000);*/
								sendMsgVoice(voiceFile,String.valueOf((afterTime - beforeTime) / 1000),mFileName);
							}

							// messageInput.setText("");
						} catch (Exception e) {
							//showToast("信息发送失败");
							// messageInput.setText(message);
						}
						hideSoftInputView();//隐藏软键盘
					}
					iv_record.setImageResource(R.drawable.chat_icon_voice1);
					break;
				default:
					break;
				}
				return false;
			}
		});
		/*//切换语音 2018-03-02
		*jcd注释
		btn_chat_voice=(Button)findViewById(R.id.btn_chat_voice);
		btn_chat_voice.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				btn_chat_voice.setVisibility(View.GONE);
				btn_chat_keyboard.setVisibility(View.VISIBLE);
				input.setVisibility(View.GONE);
				btn_speak.setVisibility(View.VISIBLE);
				send.setEnabled(false);
			}
		});*/
		btn_chat_keyboard=(Button)findViewById(R.id.btn_chat_keyboard);
		btn_chat_keyboard.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				btn_chat_voice.setVisibility(View.VISIBLE);
				btn_chat_keyboard.setVisibility(View.GONE);
				input.setVisibility(View.VISIBLE);
				btn_speak.setVisibility(View.GONE);
				send.setEnabled(true);
			}
		});
		layout_record = (RelativeLayout) findViewById(R.id.layout_record);
		tv_voice_tips = (TextView) findViewById(R.id.tv_voice_tips);
		iv_record = (ImageView) findViewById(R.id.iv_record);
	}
	
	public void initAdd(){
		tv_pic=(TextView) findViewById(R.id.tv_pic);
		tv_video=(TextView)findViewById(R.id.tv_video);
		tv_camera=(TextView) findViewById(R.id.tv_camera);
		tv_calling=(TextView)findViewById(R.id.tv_calling);
		tv_loc=(TextView) findViewById(R.id.tv_loc);
		
		tv_pic.setOnClickListener(this);
		tv_video.setOnClickListener(this);
		tv_camera.setOnClickListener(this);
		tv_calling.setOnClickListener(this);
		tv_loc.setOnClickListener(this);
		
	}
	
	public void initData(){
		offset=0;
		listMsg=msgDao.queryMsg(YOU,I,offset);
		offset=listMsg.size();
		mLvAdapter = new ChatAdapter(this, listMsg,avatar,avatarmy);
		mListView.setAdapter(mLvAdapter);
		mListView.setSelection(listMsg.size());
	}
	
	/**
	 * 初始化表情 
	 */
	private void initViewPager() {
		int pagesize= ExpressionUtil.getPagerCount(staticFacesList.size(),columns,rows);
		// 获取页数
		for (int i = 0; i <pagesize; i++) {
			views.add(ExpressionUtil.viewPagerItem(this, i, staticFacesList,columns, rows, input));
			LayoutParams params = new LayoutParams(16, 16);
			mDotsLayout.addView(dotsItem(i), params);
		}
		FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);
		mViewPager.setAdapter(mVpAdapter);
		mDotsLayout.getChildAt(0).setSelected(true);
	}

	/**
	 * 表情页切换时，底部小圆点
	 * @param position
	 * @return
	 */
	private ImageView dotsItem(int position) {
		View layout = inflater.inflate(R.layout.message_dot_image, null);
		ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);
		iv.setId(position);
		return iv;
	}
	
	/**
	 */
	@Override
	protected void onStart() {
		super.onStart();
	}
	
	
	private void setaddsendrelation(int flag)
	{
		if(flag== R.id.image_add)//显示add
		{
			//image_add.setVisibility(View.VISIBLE);
			send.setVisibility(View.GONE);
			RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)image_face.getLayoutParams();
			params1.addRule(RelativeLayout.LEFT_OF, R.id.image_add);
			image_face.setLayoutParams(params1); //使layout更新
		}
		else if(flag== R.id.send_sms)//显示send
		{
				image_add.setVisibility(View.GONE);
				send.setVisibility(View.VISIBLE);
				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)image_face.getLayoutParams();
				params.addRule(RelativeLayout.LEFT_OF, R.id.send_sms);
		}
	}
	@Override
	public void onClick(View arg0) {
		int id=arg0.getId();
		if(id== R.id.send_sms)
		{
			String content=input.getText().toString();
			if(TextUtils.isEmpty(content)){
				return;
			}
			sendMsgText(content);
			setaddsendrelation(R.id.image_add);
		}
		else if(id== R.id.input_sms)
		{
			if(chat_face_container.getVisibility()==View.VISIBLE){
				chat_face_container.setVisibility(View.GONE);
			}
			if(chat_add_container.getVisibility()==View.VISIBLE){
				chat_add_container.setVisibility(View.GONE);
			}
		}
		else if(id== R.id.image_face)
		{
			hideSoftInputView();//隐藏软键盘
			if(chat_add_container.getVisibility()==View.VISIBLE){
				chat_add_container.setVisibility(View.GONE);
			}
			if(chat_face_container.getVisibility()==View.GONE){
				chat_face_container.setVisibility(View.VISIBLE);
			}else{
				chat_face_container.setVisibility(View.GONE);
			}
		}
		else if(id== R.id.image_add)
		{
			hideSoftInputView();//隐藏软键盘
			if(chat_face_container.getVisibility()==View.VISIBLE){
				chat_face_container.setVisibility(View.GONE);
			}
			if(chat_add_container.getVisibility()==View.GONE){
				chat_add_container.setVisibility(View.VISIBLE);
			}else{
				chat_add_container.setVisibility(View.GONE);
			}
		}
		else if(id== R.id.tv_pic)//模拟一张图片路径
		{
			getPictureFromPhoto();
		}
		else if(id== R.id.tv_video)//视频通话
		{
			String roomNumber = String.valueOf((int) (Math.random() * 10000));
			//发送信息
			//sendMsgConference(roomNumber);
			//startActivity(new Intent(thisChatActivity, TelepresenceActivity.class).putExtra("CallNumber",roomNumber));
		}
		else if(id== R.id.tv_camera)//拍照，换个美女图片吧
		{
			//sendMsgImg("http://b.hiphotos.baidu.com/image/pic/item/55e736d12f2eb93872b0d889d6628535e4dd6fe8.jpg");
			getPictureFormCamera();
		}
		else if(id== R.id.tv_calling)//电话
		{
			String roomNumber_call = String.valueOf((int) (Math.random() * 10000));
			//发送信息
			//sendMsgVoiceCall(roomNumber_call);
			//startActivity(new Intent(thisChatActivity, CallActivity.class).putExtra("Paras",new String[]{roomNumber_call,"1"}));
		}
		else if(id== R.id.tv_loc)//位置，正常情况下是需要定位的，可以用百度或者高德地图，现设置为北京坐标
		{
			sendMsgLocation("116.404,39.915");
		}
	}
	/**
	 * 执行发送消息 语音类型
	 * @param content
	 */
	void sendMsgVoice(String content,String thread,String FilePath){
		Msg msg=getChatInfoTo(content, Const.MSG_TYPE_VOICE);
		msg.setContent("");
		msg.setBak1(thread);
		msg.setBak2(FilePath);
		msg.setMsgId(msgDao.insert(msg));
		listMsg.add(msg);
		offset=listMsg.size();
		mLvAdapter.notifyDataSetChanged();
		final org.jivesoftware.smack.packet.Message msg_send=new org.jivesoftware.smack.packet.Message();
//		msg_send.setTo(YOU);
//		msg_send.setFrom(I);
		msg_send.setBody(content);
		msg_send.setType(org.jivesoftware.smack.packet.Message.Type.chat);
		msg_send.setThread(thread);
		msg_send.setSubject(msg.getType());
		msg_send.setProperty("date",msg.getDate());
		//final String message=YOU+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_VOICE+Const.SPLIT+content+Const.SPLIT+sd.format(new Date());
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					XmppUtil.sendMessage(BaseApplication.xmppConnection, msg_send, YOU);

				} catch (XMPPException e) {
					e.printStackTrace();
					Looper.prepare();
					CommUtility.showmsg(thisChatActivity,"发送失败");
					Looper.loop();
				}
			}
		}).start();
		updateSession(Const.MSG_TYPE_TEXT,"[语音]");
	}
	/**
	 * 执行发送消息 图片类型
	 */
	void sendMsgImg(String content,String ImgPath){
		Msg msg=getChatInfoTo(content, Const.MSG_TYPE_IMG);
		msg.setBak2(ImgPath);//图片路径
		//如果是图片就不往数据库存了直接 只是存放路径
		msg.setContent("");
		msg.setMsgId(msgDao.insert(msg));
		listMsg.add(msg);
		offset=listMsg.size();
		mLvAdapter.notifyDataSetChanged();
		final org.jivesoftware.smack.packet.Message msg_send=new org.jivesoftware.smack.packet.Message();
//		msg_send.setTo(YOU);
//		msg_send.setFrom(I);
		msg_send.setBody(content);
		msg_send.setType(org.jivesoftware.smack.packet.Message.Type.chat);
		msg_send.setSubject(msg.getType());
		msg_send.setProperty("date",msg.getDate());
		//final String message=YOU+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_IMG+Const.SPLIT+imgpath+Const.SPLIT+sd.format(new Date());
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					XmppUtil.sendMessage(BaseApplication.xmppConnection, msg_send, YOU);
				} catch (XMPPException e) {
					e.printStackTrace();
					Looper.prepare();
					CommUtility.showmsg(ChatActivity.this,"发送失败");
					Looper.loop();
				}
			}
		}).start();
		updateSession(Const.MSG_TYPE_TEXT,"[图片]");
	}
	
	/**
	 * 执行发送消息 文本类型
	 * @param content
	 */
	void sendMsgText(String content){
		if (XmppUtil.code1!=null){
			if(("0").equals(XmppUtil.code1)){
				Msg msg=getChatInfoTo(content, Const.MSG_TYPE_TEXT);
				msg.setMsgId(msgDao.insert(msg));
				listMsg.add(msg);
				offset=listMsg.size();
				mLvAdapter.notifyDataSetChanged();
				input.setText("");
				//发送消息体
				final org.jivesoftware.smack.packet.Message msg_send=new org.jivesoftware.smack.packet.Message();
//		msg_send.setTo(YOU);
//		msg_send.setFrom(I);
				msg_send.setBody(content);
				msg_send.setType(org.jivesoftware.smack.packet.Message.Type.chat);
				msg_send.setSubject(msg.getType());
				msg_send.setProperty("date",msg.getDate());
				//final String message=YOU+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_TEXT+Const.SPLIT+content+Const.SPLIT+sd.format(new Date());
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							XmppUtil.sendMessage(BaseApplication.xmppConnection, msg_send, YOU);
							Intent intent = new Intent("shuaxinhaoyou");
							localBroadcastManager.sendBroadcast(intent);
						} catch (XMPPException e) {
							e.printStackTrace();
							Looper.prepare();
							CommUtility.showmsg(ChatActivity.this,"发送失败");
							Looper.loop();
						}
					}
				}).start();
				updateSession(Const.MSG_TYPE_TEXT,content);
			}else {
				Toast.makeText(ChatActivity.this,"您已掉线,请重新登录",Toast.LENGTH_LONG).show();
				return;
			}
		}else {
			Toast.makeText(ChatActivity.this,"通信服务器连接失败",Toast.LENGTH_LONG).show();

		}

	}
	/**
	 * 执行发送消息 视频会议
	 * @param content
	 */
	void sendMsgConference(String content){
		Msg msg=getChatInfoTo(content, Const.MSG_TYPE_CONFERENCECALL);
		msg.setMsgId(msgDao.insert(msg));
		listMsg.add(msg);
		offset=listMsg.size();
		mLvAdapter.notifyDataSetChanged();
		input.setText("");
		final org.jivesoftware.smack.packet.Message msg_send=new org.jivesoftware.smack.packet.Message();
//		msg_send.setTo(YOU);
//		msg_send.setFrom(I);
		msg_send.setBody(content);
		msg_send.setType(org.jivesoftware.smack.packet.Message.Type.chat);
		msg_send.setSubject(msg.getType());
		msg_send.setProperty("date",msg.getDate());
		//final String message=YOU+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_TEXT+Const.SPLIT+content+Const.SPLIT+sd.format(new Date());
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					XmppUtil.sendMessage(BaseApplication.xmppConnection, msg_send, YOU);
				} catch (XMPPException e) {
					e.printStackTrace();
					Looper.prepare();
					CommUtility.showmsg(ChatActivity.this,"发送失败");
					Looper.loop();
				}
			}
		}).start();
		updateSession(Const.MSG_TYPE_CONFERENCECALL,"[视频呼叫]");
	}
	/**
	 * 执行发送消息 视频会议
	 * @param content
	 */
	void sendMsgVoiceCall(String content){
		Msg msg=getChatInfoTo(content, Const.MSG_TYPE_VOICECALL);
		msg.setMsgId(msgDao.insert(msg));
		listMsg.add(msg);
		offset=listMsg.size();
		mLvAdapter.notifyDataSetChanged();
		input.setText("");
		final org.jivesoftware.smack.packet.Message msg_send=new org.jivesoftware.smack.packet.Message();
//		msg_send.setTo(YOU);
//		msg_send.setFrom(I);
		msg_send.setBody(content);
		msg_send.setType(org.jivesoftware.smack.packet.Message.Type.chat);
		msg_send.setSubject(msg.getType());
		msg_send.setProperty("date",msg.getDate());
		//final String message=YOU+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_TEXT+Const.SPLIT+content+Const.SPLIT+sd.format(new Date());
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					XmppUtil.sendMessage(BaseApplication.xmppConnection, msg_send, YOU);
				} catch (XMPPException e) {
					e.printStackTrace();
					Looper.prepare();
					CommUtility.showmsg(ChatActivity.this,"发送失败");
					Looper.loop();
				}
			}
		}).start();
		updateSession(Const.MSG_TYPE_CONFERENCECALL,"[语音呼叫]");
	}
	/**
	 * 执行发送消息 文本类型  位置
	 * @param content
	 */
	void sendMsgLocation(String content){
		Msg msg=getChatInfoTo(content, Const.MSG_TYPE_LOCATION);
		msg.setMsgId(msgDao.insert(msg));
		listMsg.add(msg);
		offset=listMsg.size();
		mLvAdapter.notifyDataSetChanged();
		final org.jivesoftware.smack.packet.Message msg_send=new org.jivesoftware.smack.packet.Message();
//		msg_send.setTo(YOU);
//		msg_send.setFrom(I);
		msg_send.setBody(content);
		msg_send.setType(org.jivesoftware.smack.packet.Message.Type.chat);
		msg_send.setSubject(msg.getType());
		msg_send.setProperty("date",msg.getDate());
		//final String message=YOU+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_LOCATION+Const.SPLIT+content+Const.SPLIT+sd.format(new Date());
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					XmppUtil.sendMessage(BaseApplication.xmppConnection, msg_send, YOU);
				} catch (XMPPException e) {
					e.printStackTrace();
					Looper.prepare();
					CommUtility.showmsg(ChatActivity.this,"发送失败");
					Looper.loop();
				}
			}
		}).start();
		updateSession(Const.MSG_TYPE_TEXT,"[位置]");
	}
	
	/**
	 * 发送的信息
	 *  from为收到的消息，to为自己发送的消息
	 * @param message => 接收者卍发送者卍消息类型卍消息内容卍发送时间
	 * @return
	 */
	private Msg getChatInfoTo(String message, String msgtype) {
		String time=sd.format(new Date());
		Msg msg = new Msg();
		msg.setFromUser(YOU);
		msg.setToUser(I);
		msg.setType(msgtype);
		msg.setIsComing(1);
		msg.setContent(message);
		msg.setDate(time);
		return msg;
	}
	
	void updateSession(String type,String content){
		Session session=new Session();
		session.setFrom(YOU);
		session.setTo(I);
		session.setNotReadCount("");//未读消息数量
		session.setContent(content);
		session.setTime(sd.format(new Date()));
		session.setType(type);
		if(sessionDao.isContent(YOU, I)){
			sessionDao.updateSession(session);
		}else{
			sessionDao.insertSession(session);
		}
		Intent intent=new Intent(Const.ACTION_ADDFRIEND);//发送广播，通知消息界面更新
		sendBroadcast(intent);
	}
	
	
	/**
	 * 表情页改变时，dots效果也要跟着改变
	 * */
	class PageChange implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
		@Override
		public void onPageSelected(int arg0) {
			for (int i = 0; i < mDotsLayout.getChildCount(); i++) {
				mDotsLayout.getChildAt(i).setSelected(false);
			}
			mDotsLayout.getChildAt(arg0).setSelected(true);
		}
	}

	/**
	 * 下拉加载更多
	 *//*
	@Override
	public void onRefresh() {
		List<Msg> list=msgDao.queryMsg(YOU,I,offset);
		if(list.size()<=0){
			mListView.setSelection(0);
			mListView.onRefreshCompleteHeader();
			return;
		}
		listMsg.addAll(0,list);
		offset=listMsg.size();
		mListView.onRefreshCompleteHeader();
		mLvAdapter.notifyDataSetChanged();
		mListView.setSelection(list.size());
	}
	*/
	/** 
	 * 弹出输入法窗口 
	 */  
	private void showSoftInputView(final View v) {  
	    new Handler().postDelayed(new Runnable() {  
	        @Override  
	        public void run() {  
	        	((InputMethodManager) v.getContext().getSystemService(Service.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
	        }  
	    }, 0);  
	}
	
	/**
	 * 隐藏软键盘
	 */
	public void hideSoftInputView() {
		InputMethodManager manager = ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE));
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	///////发送语音相关
	/** 开始录音 */
	private String startVoice() {
		String dir = String.valueOf(System.currentTimeMillis());
		// 设置录音保存路径
		mFileName = PATH + dir + ".amr";
		System.out.println(mFileName);
		String state = Environment.getExternalStorageState();
		if (!state.equals(Environment.MEDIA_MOUNTED)) {
			Log.i(LOG_TAG, "SD Card is not mounted,It is  " + state + ".");
		}
		File directory = new File(mFileName).getParentFile();
		if (!directory.exists() && !directory.mkdirs()) {
			Log.i(LOG_TAG, "Path to file could not be created");
		}
		CommUtility.showmsg(thisChatActivity,"开始录音");
		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
		mRecorder.setOutputFile(mFileName);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
		try {
			mRecorder.prepare();
		} catch (IOException e) {
			Log.e(LOG_TAG, "prepare() failed");
		}
		mRecorder.start();
		return dir;
	}

	/** 停止录音 */
	private void stopVoice() {
		mRecorder.stop();
		mRecorder.release();
		mRecorder = null;
		CommUtility.showmsg(thisChatActivity,"保存录音");
	}
	Toast mToast;
	public void ShowToast(final int resId) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (mToast == null) {
					mToast = Toast.makeText(
							ChatActivity.this.getApplicationContext(), resId,
							Toast.LENGTH_SHORT);
				} else {
					mToast.setText(resId);
				}
				mToast.show();
			}
		});
	}
	
	////////////发送语音相关结束
	
	/**
	 * 接收消息记录操作广播：删除复制
	 * @author baiyuliang
	 */
	private class MsgOperReciver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			int type=intent.getIntExtra("type", 0);
			final int position=intent.getIntExtra("position", 0);
			if(listMsg.size()<=0){
				return;
			}
			final Msg msg=listMsg.get(position);
			switch (type) {
			case 1://聊天记录操作
				Builder bd = new Builder(ChatActivity.this);
				String[] items=null;
				if(msg.getType().equals(Const.MSG_TYPE_TEXT)){
					items =  new String[]{"删除记录","删除全部记录","复制文字"};
				}else if(msg.getType().equals(Const.MSG_TYPE_CONFERENCECALL)){
					items =  new String[]{"删除记录","删除全部记录","进入视频会议"};
				}else if(msg.getType().equals(Const.MSG_TYPE_VOICECALL)){
					items =  new String[]{"删除记录","删除全部记录","语音通话"};
				}
				else {
					items =  new String[]{"删除记录","删除全部记录"};
				}
				bd.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						switch (arg1) {
						case 0://删除
							listMsg.remove(position);
							offset=listMsg.size();
							mLvAdapter.notifyDataSetChanged();
							msgDao.deleteMsgById(msg.getMsgId());
							break;
						case 1://删除全部
							listMsg.removeAll(listMsg);
							offset=listMsg.size();
							mLvAdapter.notifyDataSetChanged();
							msgDao.deleteAllMsg(YOU, I);
							break;
						case 2://复制
							String msgcontent=msg.getContent();
							switch (msg.getType())
							{
								case Const.MSG_TYPE_CONFERENCECALL://视频会议
									//开启视频呼叫界面

									//Intent it_conference=new Intent(thisChatActivity, TelepresenceActivity.class);
									//it_conference.putExtra("CallNumber",msgcontent);
									//thisChatActivity.startActivity(it_conference);
									break;
								case Const.MSG_TYPE_VOICECALL://语音通话
									//开启语音呼叫界面
									//Intent it_voicecall=new Intent(thisChatActivity, CallActivity.class);
									//it_voicecall.putExtra("CallNumber",msgcontent);
									//thisChatActivity.startActivity(it_voicecall);
									//thisChatActivity.startActivity(new Intent(thisChatActivity, CallActivity.class).putExtra("CallNumber",msgcontent));
									break;
								default:
									ClipboardManager cmb = (ClipboardManager) ChatActivity.this.getSystemService(ChatActivity.CLIPBOARD_SERVICE);
									cmb.setText(msg.getContent());
									Toast.makeText(getApplicationContext(), "已复制到剪切板", Toast.LENGTH_SHORT).show();
									break;
							}
							break;
						}
					}
				});
				bd.show();
				break;
			}
				
			}
	}
	
	/**
	 * 接收消息记录操作广播：删除复制
	 * @author baiyuliang
	 */
	private class NewMsgReciver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle b=intent.getBundleExtra("msg");
			Msg msg=(Msg) b.getSerializable("msg");
			listMsg.add(msg);
			offset=listMsg.size();
			mLvAdapter.notifyDataSetChanged();
		}
	}
	
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MsgListener.num="0";
		MsgListener.nicheng="null";
		unregisterReceiver(msgOperReciver);
		unregisterReceiver(newMsgReciver);
		//发送广播 刷新好友列表
		Intent intent = new Intent("shuaxinhaoyou");
		localBroadcastManager.sendBroadcast(intent);
	}
	
    @Override
    protected void onResume() {
 		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				//让输入框获取焦点
				input.requestFocus();
			}
		}, 100);
    	super.onResume();
    };
	
	/**
	 * 监听返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			 hideSoftInputView();
				if(chat_face_container.getVisibility()==View.VISIBLE){
					chat_face_container.setVisibility(View.GONE);
				}else if(chat_add_container.getVisibility()==View.VISIBLE){
					chat_add_container.setVisibility(View.GONE);
				}else{
					finish();
				}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	///----------------------------------------------------------------图片发送相关------------------------------------------------------------------
	 /* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	/* 从相册中获取照片 */
	private void getPictureFromPhoto()
	{
		Intent openphotoIntent = new Intent(Intent.ACTION_PICK);
		openphotoIntent.setType("image/*");
		startActivityForResult(openphotoIntent, PHOTO_PICKED_WITH_DATA);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{

		if (resultCode != RESULT_OK)
		{
			return;
		}

		switch (requestCode)
		{
			case CAMERA_WITH_DATA :
				Bitmap resultBitmap1 = BitmapFactory.decodeFile(tempPhotoPath);
				String time1=sd.format(new Date());
				String fileName1=String.valueOf(System.currentTimeMillis());
				String path1=SaveBitmap(resultBitmap1,fileName1);
				String PhotoContent1 = XmppUtil.GetImageStr(tempPhotoPath);
				sendMsgImg(PhotoContent1,path1);
				break;

			case PHOTO_PICKED_WITH_DATA :

				Uri originalUri = data.getData();
				//Log.i("jarlen", "originalUri = "+originalUri);
				String[] filePathColumn = {MediaStore.MediaColumns.DATA};
				Cursor cursor = thisChatActivity.getContentResolver().query(
						originalUri, filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String photoPath = cursor.getString(columnIndex);
				Bitmap resultBitmap = BitmapFactory.decodeFile(photoPath);
				String time=sd.format(new Date());
				String fileName=String.valueOf(System.currentTimeMillis());
				String path=SaveBitmap(resultBitmap,fileName);
				String PhotoContent = XmppUtil.GetImageStr(photoPath);
				sendMsgImg(PhotoContent,path);
				break;

			default :
				break;
		}

	}
	// 将生成的图片保存到内存中
	public String SaveBitmap(Bitmap bitmap, String name)
	{
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED))
		{
			File dir = new File(Constants.filePath);
			if (!dir.exists())
				dir.mkdir();
			File file = new File(Constants.filePath + name + ".jpg");
			FileOutputStream out;
			try
			{
				out = new FileOutputStream(file);
				if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out))
				{
					out.flush();
					out.close();
				}
				return file.getAbsolutePath();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		return null;
	}
	///----------------------------------------------------------------图片发送相关结束------------------------------------------------------------------
	///-----------------------------------------------------------------拍照发送相关---------------------------------------------------------------------
	String tempPhotoPath="";
/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;
	/* 从相机中获取照片 */
	private void getPictureFormCamera()
	{
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

		tempPhotoPath = FileUtils.DCIMCamera_PATH + FileUtils.getNewFileName()
				+ ".jpg";

		File mCurrentPhotoFile = new File(tempPhotoPath);

		if (!mCurrentPhotoFile.exists())
		{
			try
			{
				mCurrentPhotoFile.createNewFile();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(mCurrentPhotoFile));
		startActivityForResult(intent, CAMERA_WITH_DATA);
	}
	/////--------------------------------------------------------------拍照发送相关结束-------------------------------------------------------------------
	//视频流程
	//第一步：创建会话分组
	private void CreateRooom(String roomNo)
	{

	}
	

}
